<?php

namespace models;

class SysUsers extends BaseModel {
    protected $logName = '管理用户';
    protected $auto    = [
        ['create_time', 'time', self::MODEL_INSERT, 'function']
    ];

    /**
     * 登录用户
     *
     * @param        $account
     * @param string $password
     *
     * @return string
     */
    public function login($account, $password = '') {
        $map  = [
            'account' => $account,
        ];
        $find = $this->where($map)->find();
        if (!$find) {
            return error('用户名或密码不正确');
        }
        if (!$this->verifyPassword($password, $find['password'])) {
            return error('密码不正确');
        }
        // 校验是否有token在活动
        $token = new SysTokens();
        $token = $token->bindToken($find['id'], 1);
        if (!$token) {
            return error('登录失败 400001');
        }
        // 更新时间
        $this->where($map)->update(['last_time' => time()]);

        return success(['access_token' => $token], 0);
    }

    /**
     * 注册账号
     *
     * @param        $account
     * @param        $password
     * @param string $nickname
     *
     * @return string
     */
    public function register($account, $password, $nickname = '') {
        $map  = [
            'account' => $account,
        ];
        $find = $this->where($map)->find();
        if ($find) {
            return error('用户名已被占用');
        }
        $password = $this->generatePassword($password);
        if (!$password) {
            return error('密码获取失败');
        }
        $map['password'] = $password;
        $map['nickname'] = $nickname;
        $this->create($map);
        $status = $this->insert();
        if (!$status) {
            return error('注册失败');
        }

        return success('注册成功');
    }

    /**
     * 生成密码
     *
     * @param string $password
     *
     * @return bool|string
     */
    public function generatePassword($password = '') {
        $password = password_hash($password, PASSWORD_DEFAULT);

        return $password;
    }

    /**
     * 验证一个密码
     *
     * @param string $password 原密码
     * @param string $hash     新密码
     *
     * @return bool
     */
    public function verifyPassword($password, $hash) {
        if (!password_verify($password, $hash)) {
            return false;
        }

        return true;
    }

    /**
     * 获取用户信息
     *
     * @param        $id
     * @param string $field
     *
     * @return array|string
     */
    public function getUserInfo($id, $field = 'nickname') {
        return $this->getFind($id, $field);
    }
}
